//
//  RespositoriesViewController.m
//  monkey
//
//  Created by lidi on 15/8/4.
//  Copyright (c) 2015年 colin. All rights reserved.
//

#import "RespositoriesViewController.h"
#import "RespositoriesTableViewCell.h"
#import "YiRefreshHeader.h"
#import "YiRefreshFooter.h"
#import "DetailViewController.h"
#import "UIImageView+WebCache.h"


@interface RespositoriesViewController ()<UITableViewDelegate,UITableViewDataSource>
{
    
    YiRefreshHeader *refreshHeader;
    YiRefreshFooter *refreshFooter;
    int total;
}
@property (strong, nonatomic) IBOutlet UITableView *respositoriesTableView;
@property (strong,nonatomic) NSMutableArray *respostoriesDatas;
@property (strong,nonatomic) NSMutableArray *fansDatas;

//@property (strong, nonatomic) IBOutlet UILabel *label1;



@end

@implementation RespositoriesViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // Do any additional setup after loading the view.
    NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    //读取数据地址
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"https://api.github.com/search/repositories?q=language:objective-c&sort=stars&order=desc"]];
    
    request.HTTPMethod = @"GET";
    //请求数据
    NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        
        NSError *jsonError;
        //得到数据
        id resData = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&jsonError];
        
        if (!jsonError) {
            
            NSInteger total_count = [[resData objectForKey:@"total_count"] integerValue];
            if (total_count != 0) {
                //                //success
                NSArray *data = (NSArray *)[resData objectForKey:@"items" ];
                
                self.respostoriesDatas = [NSMutableArray array];
                [self.respostoriesDatas addObjectsFromArray:data];
                [self.respositoriesTableView reloadData];
            }
            
            else  {
                NSString *incomplete_results = [resData objectForKey:@"incomplete_results"];
            }
        }
    }];
    
    [task resume];
    self.respositoriesTableView.delegate = self;
    self.respositoriesTableView.dataSource = self;
    
    total=0;
    refreshHeader=[[YiRefreshHeader alloc] init];
    refreshHeader.scrollView=self.respositoriesTableView;
    [refreshHeader header];
    
    refreshHeader.beginRefreshingBlock=^(){
        // 后台执行：
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            sleep(2);
            dispatch_async(dispatch_get_main_queue(), ^{
                // 主线程刷新视图
                total=16;
                [self.respositoriesTableView reloadData];
                [refreshHeader endRefreshing];
            });
            
        });
        
    };
    
    // 是否在进入该界面的时候就开始进入刷新状态
    [refreshHeader beginRefreshing];
    
    
    
    
    
    
    
    // YiRefreshFooter  底部刷新按钮的使用
    refreshFooter=[[YiRefreshFooter alloc] init];
    refreshFooter.scrollView=self.respositoriesTableView;
    [refreshFooter footer];
    
    refreshFooter.beginRefreshingBlock=^(){
        // 后台执行：
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            sleep(2);
            dispatch_async(dispatch_get_main_queue(), ^{
                // 主线程刷新视图
                total=total+16;
                [self.respositoriesTableView reloadData];
                [refreshFooter endRefreshing];
            });
            
        });
        
    };
//    开启多选择模式
//    self.respositoriesTableView.allowsMultipleSelectionDuringEditing=YES;
//    开启编辑模式
//    [self.respositoriesTableView setEditing:YES animated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.respostoriesDatas.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    RespositoriesTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ListenCell"];
    
    NSDictionary *listenData = [self.respostoriesDatas objectAtIndex:indexPath.row];
    cell.numberLabel.text = [NSString stringWithFormat:@"%ld",indexPath.row+1];
    cell.netLaber.text = [listenData objectForKey:@"description" ];
    cell.ownerLabel.text = [NSString stringWithFormat:@"Owner:%@",[[listenData objectForKey:@"owner"] objectForKey:@"login"]];
    cell.nameLabel.text = [listenData objectForKey:@"name"];

    cell.weLabel.text = [listenData objectForKey:@"homepage"];
    cell.starLabel.text=[NSString stringWithFormat:@"Star:%@",[listenData objectForKey:@"stargazers_count"]];
    cell.forkLabel.text=[NSString stringWithFormat:@"Fork:%@",[listenData objectForKey:@"forks_count"]];
    
    //
//    cell.image.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[[listenData objectForKey:@"owner" ]objectForKey:@"avatar_url" ]]]];
        [cell.image sd_setImageWithURL:[NSURL URLWithString:[[listenData objectForKey:@"owner" ]objectForKey:@"avatar_url" ]]placeholderImage:[UIImage imageNamed:@"placeholder.png"]];
    
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSDictionary *listenData = [self.respostoriesDatas objectAtIndex:indexPath.row];
    
    
    NSLog(@"%@",[listenData objectForKey:@"name"]);
//    DetailViewController *detail=[[DetailViewController alloc] init];
//    RepositoryModel  *listenData = [(self.DsOfPageListObject.dsArray) objectAtIndex:indexPath.row];
    //    [self.navigationController pushViewController:detail animated:YES];
//    DetailViewController *detailViewController = [[DetailViewController alloc] init];
//    [self.navigationController pushViewController:detailViewController animated:YES];
//
}
/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{

//首先获得Cell：button的父视图是contentView，再上一层才是UITableViewCell
    UITableViewCell *cell = (UITableViewCell *)sender;
    
    //然后使用indexPathForCell方法，就得到indexPath了~
    NSIndexPath *indexPath = [self.respositoriesTableView indexPathForCell:cell];

    NSDictionary *listenData = [self.respostoriesDatas objectAtIndex:indexPath.row];
    NSLog(@"拿到选中行");
DetailViewController *detail=[segue destinationViewController];
 
    detail.name = [listenData objectForKey:@"full_name"];
    detail.userimage = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[[listenData objectForKey:@"owner" ]objectForKey:@"avatar_url" ]]]];
    detail.description1 = [listenData objectForKey:@"description" ];
    detail.foke1 = [NSString stringWithFormat:@"%@\nForks",[listenData objectForKey:@"forks_count"]];
    detail.star1 = [NSString stringWithFormat:@"%@\nStargazers",[listenData objectForKey:@"stargazers_count"]];
    detail.homepage = [listenData objectForKey:@"homepage"];
    detail.time = [listenData objectForKey:@"created_at"];
    
    
    NSError *error;
//    详情粉丝数据解析
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",[listenData objectForKey:@"contributors_url"]]]];
       NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
//IOS5自带解析类NSJSONSerialization从response中解析出数据放到字典或者数组中
NSArray *array2 = [NSJSONSerialization JSONObjectWithData:response options:NSJSONReadingMutableLeaves error:&error];
self.fansDatas = [NSMutableArray array];//设置fansDatas为一个可变数组
[self.fansDatas addObjectsFromArray:array2];
  
    //把array1数组中的元素添加到fansDatas中去
    detail.fansData1 = [[NSMutableArray alloc]init];
    [detail.fansData1 addObjectsFromArray:array2];
  NSLog(@"%@",detail.fansData1);


}    


@end
